package com.cskaoyan.service;



import com.cskaoyan.bean.pojo.Role;
import com.cskaoyan.bean.pojo.RoleExample;
import com.cskaoyan.bean.vo.RoleListVo;
import com.cskaoyan.mapper.RoleMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@Service
public class AdminRoleServiceImpl implements AdminRoleService {

    @Autowired
    RoleMapper roleMapper;

    @Override
    public Role addAdminRole(Role role) {

        //获得当前时间
        Date date = new Date();
        //对应赋值
        role.setEnabled(true);
        role.setAddTime(date);
        role.setUpdateTime(date);
        role.setDeleted(false);

        int insert = roleMapper.insert(role);

        if (insert != 0)
            return role;
        return null;
    }

    @Override
    public Role updateAdminRole(Role role) {

        //更新时间
        Date date = new Date();
        role.setUpdateTime(date);
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andIdEqualTo(role.getId());

        int i = roleMapper.updateByExampleSelective(role, roleExample);

        if (i != 0) return role;
        return null;
    }

    @Override
    public RoleListVo searchAdminRole(Integer page, Integer limit, String sort, String order, String name) {

        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        PageHelper.startPage(page, limit);
        //排序
        roleExample.setOrderByClause(sort + " " + order);

        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<Role> roles = roleMapper.selectByExample(roleExample);

        PageInfo<Role> rolePageInfo = new PageInfo<>(roles);

        RoleListVo roleListVo = new RoleListVo();
        roleListVo.setItems(roles);
        roleListVo.setTotal(rolePageInfo.getTotal());

        return roleListVo;

    }

    @Override
    public Role deleteAdminRole(Role role) {

        //更新时间
        Date date = new Date();
        role.setDeleted(true);
        role.setUpdateTime(date);
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andIdEqualTo(role.getId());

        int i = roleMapper.updateByExampleSelective(role, roleExample);

        if (i != 0) return role;
        return null;

    }
}
